import React, { useState, useEffect, useRef } from 'react';
import { View, Text, StyleSheet, Animated, Pressable, FlatList, Image, KeyboardAvoidingView, Platform } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import Icon1 from 'react-native-vector-icons/AntDesign';
import { useNavigation } from '@react-navigation/native';
import HotText from './hotText';
import SearchButton from './SearchButton';
import PostDetail from './PostDetail';
import CommentInput from './CommentInput';
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Modal } from 'react-native';
import ImageViewer from 'react-native-image-zoom-viewer';

const Pyq = () => {
  const navigation = useNavigation();
  const [refreshing, isRefresh] = useState(true);
  const [isCommentInputVisible, setIsCommentInputVisible] = useState(false);
  const [userInfo, setUserInfo] = useState({});
  const [comments, setComments] = useState([]);
  const [commentIndex, setCommentIndex] = useState(null);
  const [isImageViewVisible, setImageViewVisible] = useState(false);
  const modules = [
    { key: '1', icon: 'group', title: '匹配交友', bgColor: '#EED7F9' },
    { key: '2', icon: 'handshake-o', title: '闲置交易', bgColor: '#e5f8e5' },
    { key: '3', icon: 'bullseye', title: '美团圈圈', bgColor: '#FFFACD' },
    { key: '4', icon: 'bullhorn', title: '朵朵招聘', bgColor: '#D7DFF9' },
  ];
  // 测试数据
  // const messages = Array.from({ length: 20 }, (_, i) => ({
  //   id: String(i),
  //   username: `用户${i + 1}`,
  //   avatar: 'https://placekitten.com/200/200',
  //   text: `这是消息内容${i + 1}`,
  //   image: 'assets/profile.jpg',
  // }));

  const [currentPostIndex, setCurrentPostIndex] = useState(0);
  const [apiResponse, setApiResponse] = useState(null);
  const [postID, setPostID] = useState(null);
  const [time, setTime] = useState('');
  const [likes, setLikes] = useState([]);
  const [liked, setLiked] = useState([]);
  const [view, setView] = useState([]);
  const [mark, setMarked] = useState([]);
  const [hotPosts, setHotPosts] = useState([]);

  const fadeAnim = useRef(new Animated.Value(0)).current;
  const handleDeletePost = (index) => {
    axios.post('http://47.111.227.58:3000/dynamic/deleteUserDynamic', {
      id: index
    })
      .then(res => {
        console.log(res.data);
        getDynamicList()
      })
      .catch(error => {
        console.error(error);
      });
  }
  const getHotPost = () => {
    axios.get('http://47.111.227.58:3000/dynamic/getDynamicView')
      .then(res => {
        // console.log(res.data);
        setHotPosts(res.data.results);
      })
      .catch(error => {
        console.error(error);
      });
  }
  const getDynamicList = () => {
    axios.get('http://47.111.227.58:3000/dynamic/getdynamic').then(res => {
      // console.log(res.data);
      setApiResponse(res.data.results)
      const initialLikes = res.data.results.map(item => item.likes);
      setLikes(initialLikes);
      const initialLiked = res.data.results.map(item => item.likedUsers?.split(',').includes(userInfo.username));
      setLiked(initialLiked);
      const initialView = res.data.results.map(item => item.view);
      setView(initialView)
      const initialComments = res.data.results.map(item => item.comments);
      setComments(initialComments);
      const initialMarked = res.data.results.map(item => item.markUsers?.split(',').includes(userInfo.username));
      setMarked(initialMarked);
      isRefresh(false);
    })
  }
  const handleRefresh = () => {
    isRefresh(true);
    getDynamicList();
  }
  const handleLike = (index) => {
    console.log(liked)
    if (liked[index]) {
      // 如果用户已经点过赞，那么再次点击就取消点赞
      let newLikes = [...likes];
      newLikes[index] = Number(newLikes[index]) - 1;
      setLikes(newLikes);
      let newLiked = [...liked];
      newLiked[index] = false;
      setLiked(newLiked);
      axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicLikes', {
        data: {
          id: apiResponse[index].id,
          likes: newLikes[index]
        }
      }).then(res => {
        console.log(res.data);
        // 更新点赞用户列表
        axios.post('http://47.111.227.58:3000/dynamic/updateLikedUsers', {
          postId: apiResponse[index].id,
          userId: userInfo.username
        }).then(res => {
          console.log(res.data);
        });
      });
    } else {
      // 如果用户还没点过赞，那么点击就增加点赞
      let newLikes = [...likes];
      newLikes[index] = Number(newLikes[index]) + 1;
      setLikes(newLikes);
      let newLiked = [...liked];
      newLiked[index] = true;
      setLiked(newLiked);
      axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicLikes', {
        data: {
          id: apiResponse[index].id,
          likes: newLikes[index]
        }
      }).then(res => {
        console.log(res.data);
        // 更新点赞用户列表
        axios.post('http://47.111.227.58:3000/dynamic/updateLikedUsers', {
          postId: apiResponse[index].id,
          userId: userInfo.username
        }).then(res => {
          console.log(res.data);
        });
      });
    }
  };
  const handleMarked = (index) => {
    if (mark[index]) {
      let newMarked = [...mark];
      newMarked[index] = false;
      setMarked(newMarked);
      axios.post('http://47.111.227.58:3000/dynamic/updateMarkUsers', {
        postId: apiResponse[index].id,
        userId: userInfo.username
      }).then(res => {
        console.log(res.data);
      });
    } else {
      let newMarked = [...mark];
      newMarked[index] = true;
      setMarked(newMarked);
      axios.post('http://47.111.227.58:3000/dynamic/updateMarkUsers', {
        postId: apiResponse[index].id,
        userId: userInfo.username
      }).then(res => {
        console.log(res.data);
      });
    }
  };
  const handlePostClick = (postId, index) => {
    navigation.navigate('PostDetail', { postId: postId });
    let newView = [...view];
    newView[index] = Number(newView[index]) + 1;
    setView(newView);
    axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicView', {
      data: {
        id: apiResponse[index].id,
        view: newView[index]
      }
    }).then(res => {
      console.log(res.data);
    });
  };


  useEffect(() => {
    (async () => {
      isRefresh(true);
      // getDynamicList()
      const currentTime = getFormattedCurrentTime();
      setTime(currentTime)
      const userinfo = await AsyncStorage.getItem('userInfo');
      if (userinfo) {
        setUserInfo(JSON.parse(userinfo))
      }
    })();
  }, []);
  useEffect(() => {
    if (userInfo.username) {
      getDynamicList();
      getHotPost()
    }
  }, [userInfo]);
  useEffect(() => {
    const intervalId = setInterval(() => {
      // 淡出当前热搜
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 500,
        useNativeDriver: true,
      }).start(() => {
        // 更新热搜索引
        setCurrentPostIndex(prevIndex => (prevIndex + 1) % hotPosts.length);
        // console.log(hotPosts)
        // console.log(apiResponse[0].desc)
        // 淡入新的热搜
        Animated.timing(fadeAnim, {
          toValue: 1,
          duration: 500,
          useNativeDriver: true,
        }).start();
      });
    }, 2000);
    return () => clearInterval(intervalId);
  }, [hotPosts]);
  // 点击非评论输入框区域隐藏评论输入框的函数
  const handleHideCommentInput = () => {
    if (isCommentInputVisible) {
      setIsCommentInputVisible(false);
    }
  };
  const getFormattedCurrentTime = () => {
    const now = new Date(); // 获取当前时间
    const year = now.getFullYear(); // 年
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月，月份是从0开始计数的
    const day = now.getDate().toString().padStart(2, '0'); // 日
    const hours = now.getHours().toString().padStart(2, '0'); // 时
    const minutes = now.getMinutes().toString().padStart(2, '0'); // 分
    const seconds = now.getSeconds().toString().padStart(2, '0'); // 秒

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  const onCommentSubmit = (comment) => {
    console.log('评论提交：', comment);
    // console.log(userInfo)
    const currentTime = getFormattedCurrentTime();
    setTime(currentTime)

    if (comment != '') {
      axios.post('http://47.111.227.58:3000/dynamic/addcomments', {
        data: {
          dy_id: postID,
          username: userInfo.username,
          phone: userInfo.phone,
          userImg: userInfo.imgUrl,
          content: comment,
          uploadTime: time
        }
      }).then(res => {
        console.log(res.data)
        let newComment = [...comments];
        newComment[commentIndex] = Number(newComment[commentIndex]) + 1;
        setComments(newComment);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicComments', {
          data: {
            id: postID,
            comment: newComment[commentIndex]
          }
        }).then(res => {
          console.log(res.data);
          axios.post('http://47.111.227.58:3000/dynamic/updataIdCharacter', {
            data: {
              character: Number(userInfo.characters) + 1,
              id: userInfo.id
            }
          }).then(res => {
            console.log(res.data);
            userInfo.characters = Number(userInfo.characters) + 1
            AsyncStorage.setItem('userInfo', JSON.stringify(userInfo));
          });
        });
      })
    }
    setIsCommentInputVisible(false);
  }
  const renderItem = ({ item, index }) => {
    return (
      <Pressable onPress={() => handlePostClick(item.id, index)}>
        <View style={styles.messageItem}>
          <View style={styles.messageHeader}>
            <Image style={styles.avatar} source={{ uri: item.userImg }} />
            <Text style={styles.username}>{item.username}</Text>
            <Text style={styles.uploadTime}>{item.uploadTime}</Text>
          </View>
          <Text style={styles.messageText}>{item.desc}</Text>
          {/* <Pressable onPress={() => {console.log(item);setImageViewVisible(true)}}> */}
          {item.imgUrl && (
            <Image style={styles.messageImage} source={{ uri: item.imgUrl }} />
          )}
          {/* </Pressable> */}
          {/* <Pressable onPress={() => setImageViewVisible(false)}>
            <Modal visible={isImageViewVisible} transparent={true}>
              <ImageViewer imageUrls={[{ url: item.imgUrl }]} />
            </Modal>
          </Pressable> */}
          <Text style={styles.boardText}>#{item.board}</Text>
          <View style={styles.interactionBar}>
            <View style={styles.leftInteractions}>
              <Pressable style={styles.interactionButton} onPress={() => handleMarked(index)}>
                <Icon1 name={mark[index] ? 'tags' : 'tagso'} size={18} color={mark[index] ? '#5D81D0' : '#777777'} style={{ marginRight: 5 }} />
                <Text style={{ color: mark[index] ? '#5D81D0' : '#777777' }}>{mark[index] ? '弃坑' : '马住'}</Text>
              </Pressable>
              <Pressable style={styles.interactionButton}>
                <Icon name="certificate" size={18} color="#b8b8b8" style={{ marginRight: 5 }} />
                <Text>赞赏</Text>
              </Pressable>
              <Pressable style={styles.interactionButton} onPress={() => handleLike(index)}>
                <Icon name={liked[index] ? 'thumbs-up' : 'thumbs-o-up'} size={18} color={liked[index] ? '#FE4F37' : '#777777'} style={{ marginRight: 5 }} />
                <Text style={{ color: liked[index] ? '#FE4F37' : '#777777' }}>{likes[index] > 0 ? likes[index] : '点赞'}</Text>
              </Pressable>
            </View>
            <View style={styles.rightInteractions}>
              <Pressable
                style={styles.rightInteraction}
                onPress={() => { setCommentIndex(index); setPostID(item.id); setIsCommentInputVisible(true) }}
              >
                <Icon name="pencil-square-o" size={18} color="#b8b8b8" style={{ marginRight: 5, marginLeft: 5 }} />
                <Text style={{ marginRight: 5 }}>{comments[index] > 0 ? comments[index] : '评论'}</Text>
              </Pressable>
              {item.username === userInfo.username && (
                <Pressable onPress={() => handleDeletePost(item.id)} style={styles.rightInteraction1}>
                  <Text>删除</Text>
                </Pressable>
              )}
            </View>
          </View>
        </View>
      </Pressable>
    );
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
    >
      {/* 热搜横条区域 */}
      <Pressable onPress={() => navigation.navigate('hotText')}>
        <View style={styles.hotSearchBar}>
          <View style={styles.hotSearchLeft}>
            <Text style={styles.hotSearchText}>十大热帖</Text>
          </View>
          <View style={styles.hotSearchRight}>
            <Animated.Text style={[styles.hotPostTitle, { opacity: fadeAnim }]}>
              {hotPosts?.[currentPostIndex]?.desc || '默认值'}
            </Animated.Text>
          </View>
        </View>
      </Pressable>
      {/* 四个模块分区 */}
      <View style={styles.modulesContainer}>
        {modules.map(module => (
          <View key={module.key} style={[styles.moduleItem, { backgroundColor: module.bgColor }]}>
            <View style={styles.moduleIcon}>
              <Icon name={module.icon} size={20} color="#333" />
            </View>
            <Text style={styles.moduleTitle}>{module.title}</Text>
          </View>
        ))}
      </View>
      <View style={styles.blank}></View>
      {/* 消息列表 */}
      <FlatList
        data={apiResponse}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        refreshing={refreshing}
        onRefresh={handleRefresh}
      />
      {/* 搜索按钮 */}
      <SearchButton navigateToSearch={() => navigation.navigate('Search')} />
      {isCommentInputVisible && (
        <>
          <Pressable
            style={StyleSheet.absoluteFill}
            activeOpacity={1}
            onPress={handleHideCommentInput}
          />
          <CommentInput
            onCommentSubmit={onCommentSubmit}
            isKeyboardVisible={isCommentInputVisible}
            setIsKeyboardVisible={setIsCommentInputVisible}
          />
        </>
      )}
    </KeyboardAvoidingView>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
  hotSearchBar: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    height: 60,
    marginTop: 10,
    borderRadius: 5,
    paddingLeft: 10,
    paddingRight: 10,
  },
  hotSearchLeft: {
    backgroundColor: '#EB4040',
    borderRadius: 5,
    height: '100%',
    width: '20%',
    alignItems: 'center',
    justifyContent: 'center',
  },
  hotSearchText: {
    fontSize: 14,
    alignItems: 'center',
    color: '#fff',
  },
  hotSearchRight: {
    flex: 1,
    borderRadius: 5,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#F4F4F4',
    height: '100%',
  },
  hotPostTitle: {
    fontSize: 14,
    color: '#333',
    paddingHorizontal: 10,
  },
  modulesContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    padding: 10,
  },
  moduleItem: {
    width: '47%',
    height: 50,
    alignItems: 'center',
    flexDirection: 'row',
    borderRadius: 10,
    backgroundColor: '#FFFFFF',
    boxShadow: '0px 2px 2px rgba(0, 0, 0, 0.1)',
    elevation: 3,
    margin: 5,
  },
  moduleIcon: {
    marginLeft: 20,
    marginRight: 5,
  },
  moduleTitle: {
    fontSize: 14,
    color: '#333',
    marginTop: 5,
  },
  blank: {
    height: 5,
    backgroundColor: '#F4F4F4',
  },
  messageItem: {
    backgroundColor: '#fff',
    padding: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    marginBottom: 10,
    paddingLeft: 15,
  },
  messageHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 5,
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 10,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  messageImage: {
    width: '70%',
    height: 170,
    borderRadius: 5,
    marginBottom: 5,
    borderWidth: 1,
    borderColor: '#ddd',
    marginBottom: 10,
  },
  username: {
    fontWeight: 'bold',
  },
  uploadTime: {
    // fontWeight: 'bold',
    color: '#b8b8b8',
    fontSize: 12,
    marginLeft: 'auto',
    marginRight: 5,
  },
  messageText: {
    marginBottom: 5,
  },
  boardText: {
    height: 25,
    width: 60,
    backgroundColor: '#DDE1EA',
    color: '#576B94',
    marginBottom: 5,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    fontSize: 12,
    // fontWeight: 'bold',
  },
  interactionBar: {
    flexDirection: 'row',
    justifyContent: 'space-between', // 确保内容分布在两侧
    alignItems: 'center', // 垂直居中
  },
  leftInteractions: {
    flexDirection: 'row', // 使得按钮水平排列
  },
  rightInteractions: {
    flexDirection: 'row', // 使得按钮水平排列
  },
  rightInteraction: {
    flexDirection: 'row',
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 20,
    padding: 5,
  },
  rightInteraction1: {
    flexDirection: 'row',
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 20,
    padding: 5,
    marginLeft: 2,
  },
  interactionButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingRight: 15,
  },
  commentButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 10,
    paddingRight: 10,
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 20,
    padding: 5,
  },
  commentInput: {
    borderColor: '#ccc',
  },
});

export default Pyq;

